#!/usr/bin/env node

const fs = require('fs')
const path = require('path')
const ejs = require('ejs')
const inquirer = require('inquirer')
const { type } = require('os')
const { resolve } = require('path')

inquirer.prompt([
    {
        name: 'name',
        type: 'input',
        message: 'component name?',
        validate: function(input) {
            var done = this.async(), pattern = /[a-z]/gi;

            if (!pattern.test(input)) {
                done('You need to provide a number');
                return;
            }
            done(null, true)
        }
    }, {
        name: 'type',
        type: 'list',
        message: 'Project name?',
        choices: [ "template", new inquirer.Separator(), "component" ],
        filter: function (val) {
            return val.toLowerCase();
        }
    }
])
.then(answer => {
    // 根据用户的输入结果生成文件

    // 模板目录
    const tmpDir = path.join(__dirname, 'templates')
    // 目标目录
    const destDir = process.cwd()

    // 将模板下的文件全部转换到目标目录
    fs.readdir(tmpDir, (err, files) => {
        if (err) throw err
        files.forEach(file => {
            // 通过模板引擎渲染对应的文件  yarn add ejs
            ejs.renderFile(path.join(tmpDir, file), answer, (err, result) => {
                if (err) throw err
                // 将结果写入目标文件目录
                fs.writeFileSync(path.join(destDir, 'src', file), result)
            })
        })
    })
})
